<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/5/16
 * Time: 12:11
 */

namespace app\common\model;

use app\common\cachemodel\AppConfig;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use think\Cache;
use XznsTools\cache\CacheManage;

/**
 * app公告相关模型
 */
class AppNotice extends BaseCache
{
    protected $table = 'wechatadmin.system_app_notice';
    protected $cacheModel = 'config.notice';
    const APPNOTICE = 'new_notice:';
    const CACHE_TIME = 86400 * 7;
    protected $birthNoticeId = 5;//默认生日公告id
    protected $registerPackageNoticeId = 6;//默认新手礼包

    /**
     * 获取最新公告数据
     * @param array $birth 档案生日信息
     * @param $uid int|null
     * @return array
     * @throws \Exception
     */
    public function getNewestNotice($birth, $uid = null)
    {
        $header = request()->header();
        $key = $header['app-type'] . $header['version'];
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->ZsGetIocData('list', function () use ($header)
        {
            $where = ['sv.type' => 2, 'v.type' => $header['app-type'], 'v.version_name' => 'V' . $header['version'], 'n.status' => 1];
            try
            {
                $ids = $this
                    ->alias('n')
                    ->where($where)
                    ->order('id', 'DESC')
                    ->join('wechatadmin.system_slide_version sv', 'n.id=sv.sid')
                    ->join('wechatadmin.system_app_version v', 'sv.vid=v.id')
                    ->column('n.id');
            }
            catch (\Exception $e)
            {
                $ids = [];
            }
            return array_flip_key_value($ids);
        });
        $data = $this->batchGetInfoByIds($ids);
        if ($data)
        {
            return $this->noticeDataReset($birth, $ids, $data, $uid);
        }
        return [];
    }

    /**
     * 公告框数据重组
     * @param array $birth 档案生日信息
     * @param $ids
     * @param $notice
     * @param null $uid
     * @return array
     * @throws \Exception
     */
    public function noticeDataReset($birth, $ids, $notice, $uid = null)
    {

        if ($uid && Cache::get('has_new_user:id:' . $uid) && in_array($this->registerPackageNoticeId, $ids, false))
        {   // 判断用户是否是 新注册用户 并且 有新手礼包的公告框
            Cache::rm('has_new_user:id:' . $uid);
            $id = $this->registerPackageNoticeId;
        } else if ($birth && in_array($this->birthNoticeId, $ids, false))
        {
            //判断今天是否是用户的生日
            $id = $this->birthNoticeId;
        } else
        {
            $ids = array_filter($ids, function ($val)
            {
                return !in_array($val, [$this->birthNoticeId, $this->registerPackageNoticeId], false);//过滤生日公告 或者 新手礼包
            });
            if ($ids)
            {
                $huaweiConfig = (new AppConfig())->configInfo('huawei');

                if (Util::IsHuawei())
                {
                    if ($huaweiConfig['update_test_status'] > 0)
                    {   // 公告框测试数据
                        $testUids = $huaweiConfig['update_test_account'] ? explode(',', $huaweiConfig['update_test_account']) : [];
                        if (!in_array($uid, $testUids, false))
                        {
                            foreach ($ids as $k => $idItem)
                            {
                                if ($idItem == $huaweiConfig['update_notice_id'])
                                {
                                    unset($ids[$k]);
                                }
                            }
                        }
                    }
                } else
                {
                    foreach ($ids as $k => $idItem)
                    {
                        if ($idItem == $huaweiConfig['update_notice_id'])
                        {
                            unset($ids[$k]);
                        }
                    }
                }
                if (!$ids)
                {
                    return [];
                }
                $id = max($ids);//最新公告id
            } else
            {
                return [];
            }
        }
        $isHg = Util::AppIsPassShowV1();
        if ($isHg && isset($notice[$id]['hg']) && $notice[$id]['hg'] != 1)
        {   // 合规情况 过滤合规隐藏的数据
            return [];
        }
        return [
            'id' => (int)$id,
            'type' => (int)$notice[$id]['type'],
            'img_url' => $notice[$id]['img_url'],
            'img_width' => (int)$notice[$id]['img_width'],
            'img_height' => (int)$notice[$id]['img_height'],
            'img_type' => (int)$notice[$id]['img_type'],
            'title' => $notice[$id]['title'],
            'des' => $notice[$id]['des'],
            'content' => $notice[$id]['content'],
            'btn' => $notice[$id]['btn'],
            'target' => $notice[$id]['target'],
            'link' => htmlspecialchars_decode($notice[$id]['link']),
            'sep_day' => (int)$notice[$id]['sep_day'],
            'young_model' => $notice[$id]['young_model'],
        ];
    }


    /**
     * 数据库批量获取公告信息
     * @param array $ids
     * @return array
     * @throws ApiException
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $field = 'id,type,img_url,img_width,img_height,img_type,title,des,content,btn,target,link,sep_day,young_model,hg';
        try
        {
            $data = $this
                ->field($field)
                ->where(['id' => ['in', $ids]])
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            throw new ApiException('公告信息获取失败', 200, config('code.error'));
        }
        return $data;
    }

    /**
     * 获取最新的公告信息
     */
    public function getNotice()
    {
        $header = request()->header();
        $id = false;
        if ($this->cache_on >= 1)
        {
            $id = Cache::get(self::APPNOTICE . $header['app-type'] . '_V' . $header['version']);
        }
        if ($id === false)
        {
            $where = ['sv.type' => 2, 'v.type' => $header['app-type'], 'v.version_name' => 'V' . $header['version'], 'n.status' => 1, 'id' => ['not in', [$this->birthNoticeId, $this->registerPackageNoticeId]]];
            try
            {
                $id = $this
                    ->alias('n')
                    ->where($where)
                    ->join('wechatadmin.system_slide_version sv', 'n.id=sv.sid')
                    ->join('wechatadmin.system_app_version v', 'sv.vid=v.id')
                    ->max('n.id');

                if ($this->cache_on >= 1)
                {
                    Cache::set(self::APPNOTICE . $header['app-type'] . '_V' . $header['version'], $id, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $id = 0;
            }
        }

        if ($id)
        {
            $data = $this->getNoticeInfo($id);
        } else
        {
            $data = null;
        }

        return $data;
    }

    /**
     * 获取某个公告具体信息
     */
    public function getNoticeInfo($id)
    {
        $data = false;
        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::APPNOTICE . $id);
        }
        if ($data === false)
        {
            try
            {

                $data = $this
                    ->field('id,type,img_url,img_width,img_height,img_type,title,des,content,btn,target,link,sep_day,young_model,hg')
                    ->where('id', $id)
                    ->findOrFail()->toArray();
                if ($this->cache_on >= 1)
                {
                    Cache::set(self::APPNOTICE . $id, $data, self::CACHE_TIME);
                }
                $data['link'] = htmlspecialchars_decode($data['link']);
            }
            catch (\Exception $e)
            {
                $data = null;
            }
        }

        return $data;
    }

}
